package com.wenhao.leetcode.hard;

/**
 * 题目：https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/
 * 买卖股票的最佳时机 III
 *
 * @author Wenhao Tong
 * @Description
 * @create 2021-07-01 13:51
 */
public class LeetCode123 {
    public static void main(String[] args) {

    }

    public int maxProfit(int[] prices) {
        int buy1 = -prices[0];
        int buy2 = -prices[0];
        int sell1 = 0;
        int sell2 = 0;
        for (int i = 1;i < prices.length;i++) {
            // 买入是亏钱
            buy1 = Math.max(buy1,-prices[i]);
            // 买入是赚钱
            sell1 = Math.max(sell1,buy1 + prices[i]);
            // 第二次如果没有合适的就相当于是当天卖了又买了，所以既没有收益也没有支出
            buy2 = Math.max(buy2,sell1 - prices[i]);
            // 买卖两次最后剩下的钱
            sell2 = Math.max(sell2,buy2 + prices[i]);
        }
        return sell2;
    }
}
